package com.ntd.study.protocol.socket;

import ntd.util.UtilArray;
import ntd.util.UtilThreadPool;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class UtilSocketServer implements UtilCollectInterface {

    private int port;
    ServerSocket serverSocket;
    private List<Socket> sockets = new ArrayList<>();

    public UtilSocketServer(int port) throws IOException {
        this.port = port;
        init();
    }

    public static void main(String[] args) throws IOException {
        new UtilSocketServer(31111) {
            @Override
            public void onMsg(byte[] b) {
                log.info(String.valueOf(b));
            }
        };
        //给客户端反馈
//        OutputStream os = s.getOutputStream();
//        String ret = "收到";
//        os.write(ret.getBytes());
//        s.close();
    }

    @Override
    public void sendMsg(byte[] msg) {
        sockets.forEach(socket -> {
            OutputStream outputStream = null;
            try {
                outputStream = socket.getOutputStream();
                outputStream.write(msg);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
        });
    }

    private void init() throws IOException {
        serverSocket = new ServerSocket(port);
        UtilThreadPool.scheduledThreadPool.execute(() -> {
            while (true) {
                Socket socket = null;
                try {
                    socket = serverSocket.accept();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.info("server-socket - 链接关闭");
                    break;
                }
                Socket finalSocket1 = socket;
                UtilThreadPool.scheduledThreadPool.execute(() -> {
                    sockets.add(finalSocket1);
                    InetAddress ip = finalSocket1.getInetAddress();
                    log.info("新连接 - ip:" + ip.getHostAddress());
                    InputStream is = null;
                    try {
                        is = finalSocket1.getInputStream();
                        final byte[] bytes = new byte[1024];
                        int len;
                        Socket finalSocket = finalSocket1;
                        while(true){
                            len = is.read(bytes);
                            if(len != -1){
                                log.info("传入数据：" + new String(bytes));
                                onMsg(UtilArray.removeLeZero(bytes), msg -> {
                                    final OutputStream outputStream;
                                    try {
                                        outputStream = finalSocket.getOutputStream();
                                        outputStream.write(UtilArray.removeLeZero(bytes));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }

    public void onMsg(byte[] removeNull, UtilCollectInterface utilSocketInterface) {
        onMsg(removeNull);
    }

    public void closeClienSocket() {
        sockets.forEach(socket -> {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 关闭连接
     */
    public void close() {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void onMsg(byte[] b) {
    }
}
